package com.chuantou.yuba.adapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.support.v4.util.LongSparseArray;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.TrendsCommentDataTO;
import com.chuantou.yuba.api.to.TrendsCommentTO;
import com.chuantou.yuba.api.to.TrendsImageTO;
import com.chuantou.yuba.api.to.TrendsTO;
import com.chuantou.yuba.ui.GalleryActivity;
import com.chuantou.yuba.ui.fragment.TrendsFragment;
import com.chuantou.yuba.ui.widget.EllipsizeTextView;
import com.chuantou.yuba.ui.widget.NineGridlayout;
import com.chuantou.yuba.ui.widget.TrendsCommentLayout;
import com.chuantou.yuba.ui.widget.TrendsCommentView;
import com.chuantou.yuba.ui.widget.ViewRecycler;
import com.chuantou.yuba.util.ActivityHelper;
import com.chuantou.yuba.util.BitmapBinder;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.DateUtil;
import com.chuantou.yuba.util.TrendsImageView;
import com.chuantou.yuba.util.UiUtil;
import com.chuantou.yuba.util.ViewHolder;
import com.easemob.applib.utils.SmileUtils;

/**
 * 个人动态Adapter
 * 
 * @author Administrator
 * 
 */
public class TrendsAdapter extends BaseAdapter {
	private List<TrendsTO> mTrends = new ArrayList<TrendsTO>();
	private ViewRecycler<TrendsImageView> mImageViewRecycler = new ViewRecycler<TrendsImageView>();
	private ViewRecycler<TrendsCommentView> mTextViewRecycler = new ViewRecycler<TrendsCommentView>();
	private LongSparseArray<Long> mExpanedContent = new LongSparseArray<Long>();
	private Context mContext;
	private int mMaxWidth;
	private int mMaxHeight;
	private TrendsFragment mFragment;
	private boolean mShowDistance = false;

	public TrendsAdapter(TrendsFragment fragment) {
		this.mFragment = fragment;
		this.mContext = mFragment.getActivity().getApplicationContext();
		mMaxWidth = UiUtil.getScreenWidth(mContext) * 2 / 3;
		mMaxHeight = UiUtil.getScreenHeight(mContext) / 3;
	}

	public void showDistance(boolean show) {
		mShowDistance = show;
	}

	@Override
	public int getCount() {
		return mTrends.size();
	}

	@Override
	public Object getItem(int position) {
		return mTrends.get(position);
	}

	public void removeTrends(TrendsTO trendsTO) {
		mTrends.remove(trendsTO);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public void addTrendsList(List<TrendsTO> trends) {
		if (trends != null && !trends.isEmpty()) {
			mTrends.addAll(trends);
		}
	}

	public void clear() {
		mTrends.clear();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = View.inflate(mContext, R.layout.trends_item, null);
		}
		TrendsTO trendsTO = mTrends.get(position);
		NetworkImageView avatarView = ViewHolder.get(convertView, R.id.avatar);
		avatarView.setTag(trendsTO);
		avatarView.setOnClickListener(mUserClickLisenter);
		BitmapBinder.bindCircularNetImage(mContext, avatarView, trendsTO.getAvatar(), R.drawable.default_avatar_round_small);
		TextView nicenameView = ViewHolder.get(convertView, R.id.nickname);
		nicenameView.setText(trendsTO.getNickname());
		nicenameView.setTag(trendsTO);
		nicenameView.setOnClickListener(mUserClickLisenter);
		TextView sexView = ViewHolder.get(convertView, R.id.sex);
		int sex = trendsTO.getSex();
		if (sex == Constants.SEX_FEMALE) {
			sexView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.sex_female, 0, 0, 0);
			sexView.setTextColor(mContext.getResources().getColor(R.color.sex_color_female));
		} else {
			sexView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.sex_male, 0, 0, 0);
			sexView.setTextColor(mContext.getResources().getColor(R.color.sex_color_male));
		}
		Date date = DateUtil.getDateObj(trendsTO.getBirthday(), DateUtil.PATTERN_YMD);
		int age = (int) ((System.currentTimeMillis() - date.getTime()) / (365L * 24 * 60 * 60 * 1000));
		sexView.setText(String.valueOf(age));
		EllipsizeTextView contentView = ViewHolder.get(convertView, R.id.content);
		View moreView = ViewHolder.get(convertView, R.id.more);
		contentView.setIndicatorView(moreView);
		boolean expand = mExpanedContent.get(trendsTO.getId(), -1L) > 0;
		String content = trendsTO.getContent();
		if (!TextUtils.isEmpty(content)) {
			contentView.setText(SmileUtils.getSmiledText(mContext, content));
			contentView.setExpand(expand);
			moreView.setTag(trendsTO);
			moreView.setOnClickListener(mMoreClickListener);
			contentView.setVisibility(View.VISIBLE);
		} else {
			contentView.setVisibility(View.GONE);
			moreView.setVisibility(View.GONE);
		}
		View imageLayout = ViewHolder.get(convertView, R.id.image_layout);
		NineGridlayout nineImageView = ViewHolder.get(convertView, R.id.image_nine_grid);
		nineImageView.setViewRecyler(mImageViewRecycler);
		TrendsImageView oneImageView = ViewHolder.get(convertView, R.id.image_one);
		List<TrendsImageTO> images = trendsTO.getImages();
		if (images == null || images.isEmpty()) {
			imageLayout.setVisibility(View.GONE);
			nineImageView.setImages(null);
		} else {
			imageLayout.setVisibility(View.VISIBLE);
			if (images.size() == 1) {
				nineImageView.setImages(null);
				nineImageView.setVisibility(View.GONE);
				oneImageView.setVisibility(View.VISIBLE);
				TrendsImageTO imageTO = images.get(0);
				String path = imageTO.getImage();
				oneImageView.setTag(path);
				oneImageView.setOnClickListener(mOneClickListener);
				// 计算这张图片的宽度和高度
				int imageWidth = imageTO.getWidth();
				int imageHeight = imageTO.getHeight();
				int destWith = 0;
				int destHeight = 0;
				if (imageWidth > mMaxWidth || imageHeight > mMaxHeight) {
					if (imageWidth > mMaxWidth && imageHeight > mMaxHeight) {
						float ratioW = mMaxWidth * 1.0f / imageWidth;
						float ratioH = mMaxHeight * 1.0f / imageHeight;
						float ratio = Math.min(ratioW, ratioH);
						destWith = (int) (ratio * imageWidth);
						destHeight = (int) (ratio * imageHeight);
					} else if (imageWidth > mMaxWidth) {
						destWith = mMaxWidth;
						destHeight = (int) (mMaxWidth * 1.0f / imageWidth * imageHeight);
					} else {
						destHeight = mMaxHeight;
						destWith = (int) (mMaxHeight * 1.0f / imageHeight * imageWidth);
					}
				} else {
					destWith = imageWidth;
					destHeight = imageHeight;
				}
				FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(destWith, destHeight, Gravity.TOP | Gravity.LEFT);
				oneImageView.setLayoutParams(layoutParams);
				BitmapBinder.bindNetImage(mContext, oneImageView, images.get(0).getImage(), R.drawable.default_image_big, false);
			} else {
				nineImageView.setImages(images);
				nineImageView.setVisibility(View.VISIBLE);
				oneImageView.setVisibility(View.GONE);
			}
		}
		TextView deleteView = ViewHolder.get(convertView, R.id.delete);
		if (mFragment.getCurrentUid() == trendsTO.getUid()) {
			deleteView.setVisibility(View.VISIBLE);
			deleteView.setTag(trendsTO);
			deleteView.setOnClickListener(mDeleteTrendsListener);
		} else {
			deleteView.setTag(null);
			deleteView.setOnClickListener(null);
			deleteView.setVisibility(View.GONE);
		}
		TextView timeView = ViewHolder.get(convertView, R.id.time);
		String time = DateUtils.formatDateTime(mContext, trendsTO.getSendTime() * 1000, DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
				| DateUtils.FORMAT_ABBREV_ALL);
		timeView.setText(time);
		ImageView replyBtnView = ViewHolder.get(convertView, R.id.reply_button);
		replyBtnView.setTag(trendsTO);
		replyBtnView.setOnClickListener(mReplyClickListener);
		ImageView likeBtnView = ViewHolder.get(convertView, R.id.like_button);
		boolean isLike = trendsTO.isLike();
		likeBtnView.setSelected(isLike);
		likeBtnView.setTag(trendsTO);
		likeBtnView.setOnClickListener(mLikeClickListener);
		TextView likeCountView = ViewHolder.get(convertView, R.id.like_count);
		int likeCount = trendsTO.getLikeCount();
		if (likeCount > 0) {
			likeCountView.setVisibility(View.VISIBLE);
			likeCountView.setText(String.valueOf(likeCount));
		} else {
			likeCountView.setVisibility(View.GONE);
			likeCountView.setText("");
		}
		TrendsCommentLayout commentLayout = ViewHolder.get(convertView, R.id.comments);
		commentLayout.setViewRecycler(mTextViewRecycler);
		commentLayout.setTrendsFragment(mFragment);
		commentLayout.setTrendsTO(trendsTO);
		TextView fastCommentView = ViewHolder.get(convertView, R.id.fast_comment);
		List<TrendsCommentTO> comments = trendsTO.getComments();
		TextView commentMoreView = ViewHolder.get(convertView, R.id.comment_more);
		commentMoreView.setTag(trendsTO);
		commentMoreView.setOnClickListener(mCommentMoreListener);
		commentLayout.setIndicatorView(commentMoreView);
		if (comments == null || comments.isEmpty()) {
			commentLayout.setVisibility(View.GONE);
			commentLayout.setComments(null, 0);
			fastCommentView.setVisibility(View.GONE);
		} else {
			commentLayout.setVisibility(View.VISIBLE);
			commentLayout.setComments(comments, trendsTO.getCommentCount());
			fastCommentView.setVisibility(View.VISIBLE);
		}
		fastCommentView.setTag(trendsTO);
		fastCommentView.setOnClickListener(mReplyClickListener);
		TextView locationVeiw = ViewHolder.get(convertView, R.id.location);
		String address = trendsTO.getAddress();
		if (mShowDistance) {
			locationVeiw.setVisibility(View.VISIBLE);
			String distance = mContext.getString(R.string.distance_format, formatDistance(trendsTO.getDistance()));
			if (!TextUtils.isEmpty(address)) {
				address = address + "(" + distance + ")";
				locationVeiw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.trends_list_location_tag, 0, 0, 0);
			} else {
				address = distance;
				locationVeiw.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
			}
			locationVeiw.setText(address);
		} else {
			if (TextUtils.isEmpty(address)) {
				locationVeiw.setVisibility(View.GONE);
			} else {
				locationVeiw.setVisibility(View.VISIBLE);
				locationVeiw.setText(address);
			}
		}
		return convertView;
	}

	protected String formatDistance(double distance) {
		DecimalFormat format = new DecimalFormat();
		format.setMaximumFractionDigits(2);
		format.setMinimumFractionDigits(0);
		return format.format(distance);
	}

	private OnClickListener mMoreClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (UiUtil.isFastDoubleClick())
				return;
			Object obj = v.getTag();
			if (obj != null && obj instanceof TrendsTO) {
				TrendsTO trends = (TrendsTO) obj;
				ViewGroup parent = (ViewGroup) v.getParent();
				mExpanedContent.put(trends.getId(), trends.getId());
				EllipsizeTextView textView = (EllipsizeTextView) parent.findViewById(R.id.content);
				textView.setExpand(true);
			}
		}
	};

	private OnClickListener mCommentMoreListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (UiUtil.isFastDoubleClick())
				return;
			Object obj = v.getTag();
			if (obj != null && obj instanceof TrendsTO) {
				final TrendsTO trends = (TrendsTO) obj;
				String url = UriHelper.getTrendsCommentListUrl();
				HashMap<String, String> params = new HashMap<String, String>();
				params.put(UriHelper.PARAMS_ID, String.valueOf(trends.getId()));
				GsonRequest<TrendsCommentDataTO> request = new GsonRequest<TrendsCommentDataTO>(Method.POST, url, new Listener<TrendsCommentDataTO>() {

					@Override
					public void onResponse(TrendsCommentDataTO response) {
						if (mFragment == null || mFragment.getActivity() == null)
							return;
						if (response != null && response.isSuccess()) {
							List<TrendsCommentTO> comments = response.getComments();
							trends.setComments(comments);
							notifyDataSetChanged();
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {

					}

				}, params, TrendsCommentDataTO.class);
				RequestManager.startRequest(mContext, request);
			}
		}
	};

	private OnClickListener mDeleteTrendsListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (UiUtil.isFastDoubleClick())
				return;
			Object obj = v.getTag();
			if (obj != null && obj instanceof TrendsTO) {
				TrendsTO trends = (TrendsTO) obj;
				if (mFragment != null) {
					mFragment.deleteTrends(trends);
				}
			}
		}
	};

	private OnClickListener mOneClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Object obj = v.getTag();
			if (obj != null && obj instanceof String) {
				String path = String.valueOf(obj);
				ArrayList<String> paths = new ArrayList<String>();
				paths.add(path);
				GalleryActivity.start(mContext, paths, 0);
			}
		}
	};

	private OnClickListener mLikeClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			v.setClickable(false);
			if (UiUtil.isFastDoubleClick())
				return;
			Object obj = v.getTag();
			if (obj != null && obj instanceof TrendsTO) {
				TrendsTO trends = (TrendsTO) obj;
				ViewGroup parent = (ViewGroup) v.getParent();
				ImageView likeBtnView = (ImageView) v;
				TextView likeCountView = (TextView) parent.findViewById(R.id.like_count);
				mFragment.likeTrends(likeBtnView, likeCountView, trends);
			}
		}
	};

	private OnClickListener mReplyClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Object obj = v.getTag();
			if (obj != null && obj instanceof TrendsTO) {
				TrendsTO trends = (TrendsTO) obj;
				if (mFragment != null) {
					mFragment.showReplyPopup(trends, 0, null);
				}
			}
		}
	};

	private OnClickListener mUserClickLisenter = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Object obj = v.getTag();
			if (obj != null && obj instanceof TrendsTO) {
				TrendsTO trends = (TrendsTO) obj;
				ActivityHelper.toProfileActivity(mFragment.getActivity(), trends.getUid());
			}
		}
	};
}
